var data = {};
var address = [];
var nim;
var chatroom;

var chatroomId = location.href.split("?")[1].split("=")[1];
var sessUser = JSON.parse(localStorage.getItem('userInfo') ).data;
var appKey = '1651e58661c3fe50e5b01abaa270a9f8';
var userInfo = {
    account: sessUser.uuid,
    token: sessUser.imToken,
    chatroomId:chatroomId,
    appKey:appKey
}
var  Netcall = WebRTC;
NIM.use(WebRTC);
var  netcall = '' ;  
function initNIM() {
    nim = NIM.getInstance({
        // 初始化SDK
        //debug: true,
        appKey: appKey,
        account: userInfo.account,
        token: userInfo.token,
        customTag: 'PC',
        onconnect: onConnect,
        onerror: onError,
        onwillreconnect: onWillReconnect,
        ondisconnect: onDisconnect,
        // 多端登录
        onloginportschange: onLoginPortsChange,
        // 用户关系
        onblacklist: onBlacklist,
        onsyncmarkinblacklist: onMarkInBlacklist,
        onmutelist: onMutelist,
        onsyncmarkinmutelist: onMarkInMutelist,
        // 好友关系
        onfriends: onFriends,
        onsyncfriendaction: onSyncFriendAction,
        // 用户名片
        onmyinfo: onMyInfo,
        onupdatemyinfo: onUpdateMyInfo,
        onusers: onUsers,
        onupdateuser: onUpdateUser,
        // 机器人列表的回调
        onrobots: onRobots,
        // 群组
        onteams: onTeams,
        onsynccreateteam: onCreateTeam,
        onUpdateTeam: onUpdateTeam,
        onteammembers: onTeamMembers,
        // onsyncteammembersdone: onSyncTeamMembersDone,
        onupdateteammember: onUpdateTeamMember,
        // 群消息业务已读通知
        onTeamMsgReceipt:onTeamMsgReceipt,
        // 会话
        onsessions: onSessions,
        onupdatesession: onUpdateSession,
        // 消息
        onroamingmsgs: onRoamingMsgs,
        onofflinemsgs: onOfflineMsgs,
        onmsg: onMsg,
        // 系统通知
        onofflinesysmsgs: onOfflineSysMsgs,
        onsysmsg: onSysMsg,
        onupdatesysmsg: onUpdateSysMsg,
        onsysmsgunread: onSysMsgUnread,
        onupdatesysmsgunread: onUpdateSysMsgUnread,
        onofflinecustomsysmsgs: onOfflineCustomSysMsgs,
        oncustomsysmsg: onCustomSysMsg,
        // 收到广播消息
        onbroadcastmsg: onBroadcastMsg,
        onbroadcastmsgs: onBroadcastMsgs,
        // 同步完成
        onsyncdone: onSyncDone
    });
}


function onConnect() {
    console.log('连接成功');
   
   
}

function onWillReconnect(obj) {
    // 此时说明 `SDK` 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
    console.log('即将重连');
    // console.log(obj.retryCount);
    // console.log(obj.duration);
}
function onDisconnect(error) {
    // 此时说明 `SDK` 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面
    console.log('丢失连接');
    console.log(error);
    location.href = "login.html";
    if (error) {
        switch (error.code) {
        // 账号或者密码错误, 请跳转到登录页面并提示错误
        case 302:
            break;
        // 被踢, 请提示错误后跳转到登录页面
        case 'kicked':
            location.href = "login.html";
            break;
        default:
            break;
        }
    }
}
function onError(error) {
    //console.log(error);
}

function onLoginPortsChange(loginPorts) {
    //console.log('当前登录帐号在其它端的状态发生改变了', loginPorts);
}

function onBlacklist(blacklist) {
    //console.log('收到黑名单', blacklist);
    data.blacklist = nim.mergeRelations(data.blacklist, blacklist);
    data.blacklist = nim.cutRelations(data.blacklist, blacklist.invalid);
    refreshBlacklistUI();
}
function onMarkInBlacklist(obj) {
    // console.log(obj);
    // console.log(obj.account + '被你在其它端' + (obj.isAdd ? '加入' : '移除') + '黑名单');
    if (obj.isAdd) {
        addToBlacklist(obj);
    } else {
        removeFromBlacklist(obj);
    }
}
function addToBlacklist(obj) {
    data.blacklist = nim.mergeRelations(data.blacklist, obj.record);
    refreshBlacklistUI();
}
function removeFromBlacklist(obj) {
    data.blacklist = nim.cutRelations(data.blacklist, obj.record);
    refreshBlacklistUI();
}
function refreshBlacklistUI() {
    // 刷新界面
}
function onMutelist(mutelist) {//静音
    data.mutelist = nim.mergeRelations(data.mutelist, mutelist);
    data.mutelist = nim.cutRelations(data.mutelist, mutelist.invalid);
    refreshMutelistUI();
}
function onMarkInMutelist(obj) {
    console.log(obj.account + '被你' + (obj.isAdd ? '加入' : '移除') + '静音列表');
    if (obj.isAdd) {
        addToMutelist(obj);
    } else {
        removeFromMutelist(obj);
    }
}
function addToMutelist(obj) {
    data.mutelist = nim.mergeRelations(data.mutelist, obj.record);
    refreshMutelistUI();
}
function removeFromMutelist(obj) {
    data.mutelist = nim.cutRelations(data.mutelist, obj.record);
    refreshMutelistUI();
}
function refreshMutelistUI() {
    // 刷新界面
}

function onFriends(friends) {//好友列表
    data.friends = nim.mergeFriends(data.friends, friends);
    data.friends = nim.cutFriends(data.friends, friends.invalid);
    refreshFriendsUI();
}
function onSyncFriendAction(obj) {
    switch (obj.type) {
    case 'addFriend':
        console.log('你在其它端直接加了一个好友' + obj.account + ', 附言' + obj.ps);
        onAddFriend(obj.friend);
        break;
    case 'applyFriend':
        console.log('你在其它端申请加了一个好友' + obj.account + ', 附言' + obj.ps);
        break;
    case 'passFriendApply':
        console.log('你在其它端通过了一个好友申请' + obj.account + ', 附言' + obj.ps);
        onAddFriend(obj.friend);
        break;
    case 'rejectFriendApply':
        console.log('你在其它端拒绝了一个好友申请' + obj.account + ', 附言' + obj.ps);
        break;
    case 'deleteFriend':
        console.log('你在其它端删了一个好友' + obj.account);
        onDeleteFriend(obj.account);
        break;
    case 'updateFriend':
        console.log('你在其它端更新了一个好友', obj.friend);
        onUpdateFriend(obj.friend);
        break;
    }
}
function onAddFriend(friend) {
    data.friends = nim.mergeFriends(data.friends, friend);
    refreshFriendsUI();
}
function onDeleteFriend(account) {
    data.friends = nim.cutFriendsByAccounts(data.friends, account);
    refreshFriendsUI();
}
function onUpdateFriend(friend) {
    data.friends = nim.mergeFriends(data.friends, friend);
    refreshFriendsUI();
}
function refreshFriendsUI() {
    // 刷新界面
}

function onMyInfo(user) {//名片
    data.myInfo = user;
    updateMyInfoUI();
}
function onUpdateMyInfo(user) {//名片更新
    data.myInfo = NIM.util.merge(data.myInfo, user);
    updateMyInfoUI();
}
function updateMyInfoUI() {
    // 刷新界面
}
function onUsers(users) {//用户名片列表
    data.users = nim.mergeUsers(data.users, users);
}
function onUpdateUser(user) {//用户名片更新
    data.users = nim.mergeUsers(data.users, user);
}
function onRobots (robots) {//机器人列表
    // 客户私有化方案不支持
    data.robots = robots;
}
function onTeams(teams) {//群列表
    data.teams = nim.mergeTeams(data.teams, teams);
    onInvalidTeams(teams.invalid);
}
function onInvalidTeams(teams) {
    data.teams = nim.cutTeams(data.teams, teams);
    data.invalidTeams = nim.mergeTeams(data.invalidTeams, teams);
    refreshTeamsUI();
}
function onCreateTeam(team) {//创建了一个群
    data.teams = nim.mergeTeams(data.teams, team);
    refreshTeamsUI();
    onTeamMembers({
        teamId: team.teamId,
        members: owner
    });
}
function refreshTeamsUI() {
    // 刷新界面
}
function onTeamMembers(teamId, members) {//群信息
    var teamId = obj.teamId;
    var members = obj.members;
    data.teamMembers = data.teamMembers || {};
    data.teamMembers[teamId] = nim.mergeTeamMembers(data.teamMembers[teamId], members);
    data.teamMembers[teamId] = nim.cutTeamMembers(data.teamMembers[teamId], members.invalid);
    refreshTeamMembersUI();
}
// function onSyncTeamMembersDone() {
//     console.log('同步群列表完成');
// }
function onUpdateTeam (team) {//群状态更新
    console.log('群状态更新', team)
}
function onUpdateTeamMember(teamMember) {//群成员更新
    onTeamMembers({
        teamId: teamMember.teamId,
        members: teamMember
    });
}
function refreshTeamMembersUI() {
    // 刷新界面
}
function onTeamMsgReceipt (teamMsgReceipts) {//群消息已读通知
}

function onSessions(sessions) {//收到回话列表
    data.sessions = nim.mergeSessions(data.sessions, sessions);
    updateSessionsUI();
}
function onUpdateSession(session) {//会话更新
    data.sessions = nim.mergeSessions(data.sessions, session);
    updateSessionsUI();
}
function updateSessionsUI() {
    // 刷新界面
}

function onRoamingMsgs(obj) {//漫游消息
    pushMsg(obj.msgs);
}
function onOfflineMsgs(obj) {//离线消息
    pushMsg(obj.msgs);
}
function onMsg(msg) {//收到消息
    pushMsg(msg);
}
function onBroadcastMsg(msg) {//收到广播消息
}
function onBroadcastMsgs(msgs) {//收到广播消息列表
}
function pushMsg(msgs) {
    if (!Array.isArray(msgs)) { msgs = [msgs]; }
    var sessionId = msgs[0].sessionId;
    data.msgs = data.msgs || {};
    data.msgs[sessionId] = nim.mergeMsgs(data.msgs[sessionId], msgs);
}

function onOfflineSysMsgs(sysMsgs) {//收到离线系统通知
    pushSysMsgs(sysMsgs);
}
function onSysMsg(sysMsg) {//收到系统通知
    pushSysMsgs(sysMsg);
}
function onUpdateSysMsg(sysMsg) {
    pushSysMsgs(sysMsg);
}
function pushSysMsgs(sysMsgs) {
    data.sysMsgs = nim.mergeSysMsgs(data.sysMsgs, sysMsgs);
    refreshSysMsgsUI();
}
function onSysMsgUnread(obj) {//收到系统通知未读数
    data.sysMsgUnread = obj;
    refreshSysMsgsUI();
}
function onUpdateSysMsgUnread(obj) {//系统通知未读数更新了
    data.sysMsgUnread = obj;
    refreshSysMsgsUI();
}
function refreshSysMsgsUI() {
    // 刷新界面
}
function onOfflineCustomSysMsgs(sysMsgs) {//收到离线自定义系统通知
    console.log("收到离线自定义系统通知")
    console.log(sysMsg)
    
}
function getChatroomDone(error, obj) {
    console.log('获取聊天室信息' + (!error?'成功':'失败'), error, obj);
    $("#my-video").css({'width':'500px','height':'300px'});
    var roomData = JSON.parse(obj.chatroom.custom);
    //console.log(obj.custom)
    console.log(roomData);
    const sessionConfig = {
        videoQuality: Netcall.CHAT_VIDEO_QUALITY_HIGH,
        videoFrameRate: Netcall.CHAT_VIDEO_FRAME_RATE_15,
        videoEncodeMode: Netcall.CHAT_VIDEO_ENCODEMODE_NORMAL,
        videoBitrate: 0,
        recordVideo: false,
        recordAudio: false,
        highAudio: false,
        bypassRtmp: false,
        rtmpUrl: '',
        rtmpRecord: false,
        splitMode: Netcall.LAYOUT_SPLITLATTICETILE
    };
    netcall
        .joinChannel({
          channelName:roomData.meetingName,//roomData.meetingName, //必填
          type: Netcall.NETCALL_TYPE_VIDEO,
          role: 0,//以互动者的身份加入
          sessionConfig: sessionConfig
        })
        .then(function(obj) {
          // 加入房间成功后的上层逻辑操作
          // eg: 开启摄像头
          // eg: 开启麦克风
          // eg: 开启本地流
          // eg: 设置音量采集、播放
          // eg: 设置视频画面尺寸等等，具体请参照p2p呼叫模式
          console.log(obj);
          netcall.startRtc().then(function() {
            // 开启麦克风
            return netcall.startDevice({
              type: Netcall.DEVICE_TYPE_AUDIO_IN
            }).catch(function(err) {
              console.log('启动麦克风失败')
              console.error(err)
            })
          })
          .then(function() {
            // 设置采集音量
            netcall.setCaptureVolume(255)
            // 开启摄像头
            return netcall.startDevice({
                type: Netcall.DEVICE_TYPE_VIDEO,
                width: 640,
                height: 480
              })
            .catch(function(err) {
              console.log('启动摄像头失败')
              console.error(err)
            })
          })
          .then(function() {
            //预览本地画面
            netcall.startLocalStream(
              document.getElementById('video1')
            )
            // 设置本地预览画面大小
            netcall.setVideoViewSize({
              width: 50,
              height: 50,
              cut:true
            })
          })
          .then(function() {
            // 设置互动者角色
            netcall.changeRoleToPlayer()
          })
          .catch(function(err) {
            console.log('发生错误')
            console.log(err)
            netcall.hangup()
          })
    });
  }
function onCustomSysMsg(sysMsg) {//收到自定义系统通知
    console.log("收到自定义系统通知")
    console.log(sysMsg);
    var that = this;
    if(sysMsg){
        var data = JSON.parse(sysMsg.content)
        /*$("#operation").show();
        $("#j-answer").click(function () {
            chatroom.getChatroom({
                done: getChatroomDone
            });
            $("#operation").hide();
            $("#sentWheat").html("挂断");
        });*/
        $("#j-hangUp").click(function () {
            $("#operation").hide();
            netcall.hangup()
            /* var content = {
                type: '1',
                value: {"command":"2","roomid":data.roomid }
            }; */
            /*var content =  {"command":"4","roomid":data.roomid }
            content = JSON.stringify(content);
            console.log(sysMsg)
            var msgId = nim.sendCustomSysMsg({
                scene: 'p2p',
                to: sysMsg.from,
                content: content,
                sendToOnlineUsersOnly: false,
                apnsText: content,
                done: sendCustomSysMsgDone
            });
            console.log('正在发送p2p自定义系统通知, id=' + msgId);
            function sendCustomSysMsgDone(error, msg) {
                console.log('发送' + msg.scene + '自定义系统通知' + (!error?'成功':'失败') + ', id=' + msg.idClient);
                console.log(error);
                console.log(msg);
            }*/
        })
        
    }
    
    
}

function onSyncDone() {//同步完成
    //获取聊天室地址
    nim.getChatroomAddress({
        chatroomId: userInfo.chatroomId,
        done: getChatroomAddressDone
    });
    
}
initNIM();

function getChatroomAddressDone(error, obj) {
    //console.log('获取聊天室地址' + (!error?'成功':'失败'), error,obj);
    /*if (!error) {
        getAddr(obj.address);
      } else {
        alert('获取连接房间地址失败');
      }*/   
    address =  obj.address
    //初始化聊天室
    chatroom = SDK.Chatroom.getInstance({
        appKey: appKey,
        account: userInfo.account,
        token: userInfo.token,

        chatroomId: userInfo.chatroomId,
        chatroomAddresses: address,
        onconnect: onChatroomConnect,
        onerror: onChatroomError,
        onwillreconnect: onChatroomWillReconnect,
        ondisconnect: onChatroomDisconnect,
        // 消息
        onmsgs: onChatroomMsgs
      });
      userInfo.address = address;
     
    //初始化界面
    page.init(userInfo);
}
